﻿using System;

namespace KPI
{
	public partial class PasswordReset : BasePage
	{
		private DataAccess.Repository.IUserRepository _UserRepository;

		protected void Page_Init(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				var p = false;

				if(TheCurrentLoginUser == null)
				{
					p = true;
				}
				else if(TheCurrentLoginUser.RoleName.Equals("unitadministrators") || TheCurrentLoginUser.RoleName.Equals("visitors"))
				{
					p = true;
				}

				if(p)
				{
					Response.Redirect("Login.aspx");
				}
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected void Page_UnLoad(object sender, EventArgs e)
		{
			if(_UserRepository != null)
			{
				((IDisposable)_UserRepository).Dispose();
			}
		}

		protected void btnUpdate_Click(object sender, EventArgs e)
		{
			if(IsValid)
			{
				if(CheckUserOldPwd())
				{
					if(_UserRepository == null)
					{
						_UserRepository = new DataAccess.Repository.UserRepository();
					}

					var theUser = _UserRepository.GetUser(TheCurrentLoginUser.UserName);

					if(theUser != null)
					{
						theUser.Password = txtPwd.Text;

						if(_UserRepository.UpdateUser(theUser, true))
						{
							ShowMessage("密码修改成功", false);
						}
						else
						{
							ShowMessage("密码修改时遇到错误，请稍后重试", true);
						}
					}
				}
				else
				{
					ShowMessage("旧密码不对，请重试", false);
				}
			}
		}

		private bool CheckUserOldPwd()
		{
			var result = false;

			if(!string.IsNullOrWhiteSpace(txtPwdOld.Text))
			{
				var userName = TheCurrentLoginUser.UserName;

				if(_UserRepository == null)
				{
					_UserRepository = new DataAccess.Repository.UserRepository();
				}

				var msg = string.Empty;

				result = _UserRepository.ValidUser(userName, txtPwdOld.Text, out msg);
			}

			return result;
		}
	}
}
